import time
from io import BytesIO

import pytest
import os
from selenium import webdriver
#从dotenv库导入load_dotenv函数
from dotenv import load_dotenv
from PIL import Image
import pytesseract
from selenium.webdriver.common.by import By

from time import sleep

#执行加载操作:会自动找项目根目录,.env文件,把里面的变量加载系统环境里
load_dotenv()


#方法二


#定一个pytest夹具,scope="session"表示整个测试会话只执行一次
#autouse=Ture表示"所有测试用列自动生效"，不用手动导入
@pytest.fixture(scope='session', autouse=True)
def green():
    #测试会话开始前执行
    print('整个项目运行前', os.getenv('base_url'))
    yield  #测试前逻辑,yield后是"测试后逻辑"
    #测试会话结束执行
    print('整个项目运行后', os.getenv('db_host'))


# #添加
# #方法三
# def pytest_add(parser):
#     parser.addoption(
#         "--env-file",
#         action="store",
#         default=".env",
#         help="指定要加载环境文件路径"
#     )
#
#
# # #获取
# def pytest_configure(config):
#     env_file = config.getoption("--evn-file") or '.env'
#
#     load_dotenv(env_file)

@pytest.fixture(scope='function', autouse=True)
def driver():
    driver1 = webdriver.Edge()
    driver1.maximize_window()

    yield driver1

    driver1.quit()


def solve_captcha_with_tesseract(image_element):
    """
    使用Tesseract OCR解析验证码
    适用于简单的验证码
    """
    # 获取验证码图片把网页上的验证码元素(图片)传成png格式的二进制数据,作用把验证码截图下来,
    captcha_screenshot = image_element.screenshot_as_png

    # 转换为PIL Image对象
    #把二进制的验证码数据,传成python处理的内存1文件
    img = Image.open(BytesIO(captcha_screenshot))

    # 预处理图片（根据实际情况调整）
    img = img.convert('L')  # 转为灰度图
    img = img.point(lambda x: 0 if x < 128 else 255, '1')  # 二值化识别验证码

    # 使用Tesseract识别
    pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'  # Windows路径
    captcha_text = pytesseract.image_to_string(img,
                                               config='--psm 8 --oem 3 -c tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
    #--psm 8：告诉 Tesseract “按单个字符 / 行识别”（适合验证码这种短文本）
    #--oem 3：用 LSTM 引擎识别（Tesseract 的一种高精度识别模式 ）
    #tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 只允许识别 大写字母 + 数字，过滤其他字符干扰（验证码一般就这些）



    #清理环境结果&返回strip去掉识别结果的首尾空白,返回“干净”的验证码文字
    return captcha_text.strip()


@pytest.fixture(scope='function')
def loginBusiness():
    driver = webdriver.Edge()
    driver.implicitly_wait(6)
    driver.maximize_window()
    driver.get('http://10.59.9.14:7003/home/login.html')
    sleep(3)
    # driver.find_element(By.ID, 'userName').clear()
    # sleep(2)
    driver.find_element(By.NAME, 'username').send_keys('17552731701')
    sleep(1)
    # driver.find_element(By.NAME, 'password').clear()
    # sleep(2)
    driver.find_element(By.NAME, 'password').send_keys('123456')
    # 手动输入验证码
    sleep(2)
    imgelement = driver.find_element(By.NAME, "code")
    print("imgeelement的样式：", imgelement)
    imgcode = solve_captcha_with_tesseract(imgelement)
    print("得到的验证码:", imgcode)
    driver.find_element(By.NAME, "code").send_keys(imgcode)
    sleep(3)
    driver.find_element(By.XPATH, "/html/body/div[4]/div/div[1]/div[2]/form/div[5]/a").click()
    sleep(6)
    yield driver
    driver.quit()


def login():
    driver1 = webdriver.Edge()
    driver1.get('http://152.136.104.73:8080/jeewms/')
    driver1.maximize_window()
    driver1.implicitly_wait(10)

    driver1.find_element(By.ID, 'userName').clear()
    driver1.find_element(By.ID, 'userName').send_keys('admin')
    driver1.find_element(By.ID, 'password').clear()
    driver1.find_element(By.ID, 'password').send_keys('llg123')
    time.sleep(10)
    driver1.find_element(By.XPATH,
                         '/html/body/div[2]/div/div/div/div/div[3]/div[1]/div/form/div[1]/div[4]/button/span').click()




    print(driver1.get_cookies())
    dic = {}
    cookkies = driver1.get_cookies()
    for i in cookkies:
        cookkies_name=i.get('name')
        if cookkies_name=='ZINDEXNUMBER':
            dic['ZINDEXNUMBER']=i.get("value")
        elif cookkies_name=="JEECGINDEXSTYLE":
            dic['JEECGINDEXSTYLE']=i.get("value")
        elif cookkies_name=="JSESSIONID":
            dic['JSESSIONID']=i.get("value")

    print(dic)
    driver1.quit()
    return dic


@pytest.fixture(scope='session')
def getheaders():
    d = login()
    heads={
        "cookie": f'JEECGINDEXSTYLE={d.get("JEECGINDEXSTYLE")}; JSESSIONID={d.get("JSESSIONID")}; ZINDEXNUMBER={d.get("ZINDEXNUMBER")}'
    }

    return heads

